<!DOCTYPE HTML>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" /> 
    <title>linux中结构体对齐 - 天地维杰网</title>
    <meta name="keywords" content="系统架构,shutdown,不与天斗,Domino,博客,程序员,架构师,笔记,技术,分享,java,Redis">
    
    <meta property="og:title" content="linux中结构体对齐">
    <meta property="og:site_name" content="天地维杰网">
    <meta property="og:image" content="/img/author.jpg"> 
    <meta name="title" content="linux中结构体对齐 - 天地维杰网" />
    <meta name="description" content="以上这个结构体占用内存多少空间呢？也许你会说，这个简单，计算每个类型的大小，将它们相加就行了，以32为平台为例，int类型占4字节，char占用1字节，所以：4 &#43; 3 &#43; 4 = 11，那么这个结构体一共占用11字节空间。好吧，那么我们就用实践来证明是否正确，我们用sizeof运算符来求出这个结构体占用内存空间大小，sizeof(MemAlign)，出乎意料的是，结果居然为12？看来我们错了？" />
     
    <link rel="shortcut icon" href="http://www.shutdown.cn/img/favicon.ico" />
    <link rel="apple-touch-icon" href="http://www.shutdown.cn/img/apple-touch-icon.png" />
    <link rel="apple-touch-icon-precomposed" href="http://www.shutdown.cn/img/apple-touch-icon.png" />
    <link href="http://www.shutdown.cn/js/vendor/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />
    <link href="http://www.shutdown.cn/js/vendor/fancybox/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />
    <link href="http://www.shutdown.cn/css/main.css" rel="stylesheet" type="text/css" />
    <link href="http://www.shutdown.cn/css/syntax.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post"},
     fancybox: true, 
    motion: true
  };
</script>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-7826003325059020" crossorigin="anonymous"></script>
</head>
<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">
<div class="container one-collumn sidebar-position-left page-home  ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"> <div class="site-meta  custom-logo ">

  <div class="custom-logo-site-title">
    <a href="http://www.shutdown.cn"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">天地维杰网</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle">人如秋鸿来有信，事若春梦了无痕</p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
    <ul id="menu" class="menu">
      
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/redis/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-battery-full"></i> <br />Redis
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/java/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-coffee"></i> <br />java
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/linux/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-linux"></i> <br />linux
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/daily/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-bug"></i> <br />日常问题
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/spring/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-child"></i> <br />Spring和Springboot
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/mac/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-fire"></i> <br />Mac相关
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/middleware/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-gavel"></i> <br />中间件
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/jiagou/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-rocket"></i> <br />架构
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/python/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-ship"></i> <br />python
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/front/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-bolt"></i> <br />前端
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/jvm/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-balance-scale"></i> <br />jvm
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/c/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-battery-empty"></i> <br />c语言
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/web3/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-web3"></i> <br />web3
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/post/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />归档
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/about/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于
          </a>
        </li>
      
      <li class="menu-item menu-item-search">
        <a href="javascript:;" class="popup-trigger"> <i class="menu-item-icon fa fa-search fa-fw"></i> <br /> 搜索</a>
      </li>
    </ul>
    <div class="site-search">
      <div class="popup">
 <span class="search-icon fa fa-search"></span>
 <input type="text" id="local-search-input">
 <div id="local-search-result"></div>
 <span class="popup-btn-close">close</span>
</div>

    </div>
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            
<section id="posts" class="posts-expand">
  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <header class="post-header">
      <h1 class="post-title" itemprop="name headline">
        <a class="post-title-link" href="http://www.shutdown.cn/post/linux-struct-align-c-packed/" itemprop="url">
        linux中结构体对齐
        </a>
      </h1>
      <div class="post-meta">
      <span class="post-time">
<span class="post-meta-item-icon">
    <i class="fa fa-calendar-o"></i>
</span>
<span class="post-meta-item-text">时间：</span>
<time itemprop="dateCreated" datetime="2016-03-22T13:04:35+08:00" content="2015-08-03">
    2015-08-03
</time>
</span> 
      

  <span class="post-category" >
  &nbsp; | &nbsp;
  <span class="post-meta-item-icon">
    <i class="fa fa-folder-o"></i>
  </span>
  <span class="post-meta-item-text">分类：</span>
  
    <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
      <a href="http://www.shutdown.cn/categories/linux" itemprop="url" rel="index">
        <span itemprop="name">linux</span>
      </a>
      &nbsp; 
    </span>
  
    <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
      <a href="http://www.shutdown.cn/categories/c" itemprop="url" rel="index">
        <span itemprop="name">c</span>
      </a>
      &nbsp; 
    </span>
  
</span>


      
 <span>
&nbsp; | &nbsp;
<span class="post-meta-item-icon">
    <i class="fa fa-eye"></i>
</span>
<span class="post-meta-item-text">转载</span>
</span>

       <span>
&nbsp; | &nbsp;
<span class="post-meta-item-icon">
    <i class="fa fa-eye"></i>
</span>
<span class="post-meta-item-text">阅读：</span>
<span class="leancloud-visitors-count">2653 字 ~6分钟</span>
</span>
      </div>
    </header>
    <div class="post-body" itemprop="articleBody">
    
    <div class="highlight"><pre style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-fallback" data-lang="fallback"> 文章系转载，便于整理和分类，原文地址：https://blog.csdn.net/suifengpiao_2011/article/details/47260085</code></pre></div>
    

    <p>linux中定义对齐字节</p>
<div class="highlight"><pre style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-c" data-lang="c"><span style="color:#204a87;font-weight:bold">typedef</span> <span style="color:#204a87;font-weight:bold">struct</span>  <span style="color:#000">sdk_handler</span> <span style="color:#000;font-weight:bold">{</span>
	<span style="color:#204a87;font-weight:bold">char</span> <span style="color:#000">comm_ver</span><span style="color:#000;font-weight:bold">[</span><span style="color:#0000cf;font-weight:bold">10</span><span style="color:#000;font-weight:bold">]</span><span style="color:#000;font-weight:bold">;</span> 
	<span style="color:#204a87;font-weight:bold">char</span> <span style="color:#000">name</span><span style="color:#000;font-weight:bold">[</span><span style="color:#0000cf;font-weight:bold">20</span><span style="color:#000;font-weight:bold">]</span><span style="color:#000;font-weight:bold">;</span>
	<span style="color:#204a87;font-weight:bold">char</span> <span style="color:#000">reserve</span><span style="color:#000;font-weight:bold">[</span><span style="color:#0000cf;font-weight:bold">20</span><span style="color:#000;font-weight:bold">]</span><span style="color:#000;font-weight:bold">;</span>
<span style="color:#000;font-weight:bold">}</span><span style="color:#000">PACKED</span>  <span style="color:#000">sdk_handler_t</span><span style="color:#000;font-weight:bold">;</span>

<span style="color:#8f5902;font-style:italic">#</span><span style="color:#8f5902;font-style:italic">define PACKED </span><span style="color:#8f5902;font-style:italic">/</span><span style="color:#8f5902;font-style:italic">/</span><span style="color:#8f5902;font-style:italic">__attribute__((aligned(1),packed))  </span><span style="color:#8f5902;font-style:italic">/</span><span style="color:#8f5902;font-style:italic">/</span><span style="color:#8f5902;font-style:italic"> 一字节对齐</span></code></pre></div>
<p>首先我们先看看下面的C语言的结构体：</p>
<div class="highlight"><pre style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-c" data-lang="c"><span style="color:#204a87;font-weight:bold">typedef</span> <span style="color:#204a87;font-weight:bold">struct</span> <span style="color:#000">MemAlign</span>  
<span style="color:#000;font-weight:bold">{</span>  
    <span style="color:#204a87;font-weight:bold">int</span> <span style="color:#000">a</span><span style="color:#000;font-weight:bold">;</span>  
    <span style="color:#204a87;font-weight:bold">char</span> <span style="color:#000">b</span><span style="color:#000;font-weight:bold">[</span><span style="color:#0000cf;font-weight:bold">3</span><span style="color:#000;font-weight:bold">]</span><span style="color:#000;font-weight:bold">;</span>  
    <span style="color:#204a87;font-weight:bold">int</span> <span style="color:#000">c</span><span style="color:#000;font-weight:bold">;</span>  
<span style="color:#000;font-weight:bold">}</span><span style="color:#000">MemAlign</span><span style="color:#000;font-weight:bold">;</span>  </code></pre></div>
<p>以上这个结构体占用内存多少空间呢？也许你会说，这个简单，计算每个类型的大小，将它们相加就行了，以32为平台为例，int类型占4字节，char占用1字节，所以：4 + 3 + 4 = 11，那么这个结构体一共占用11字节空间。好吧，那么我们就用实践来证明是否正确，我们用sizeof运算符来求出这个结构体占用内存空间大小，sizeof(MemAlign)，出乎意料的是，结果居然为12？看来我们错了？当然不是，而是这个结构体被优化了，这个优化有个另外一个名字叫“对齐”，那么这个对齐到底做了什么样的优化呢，听我慢慢解释，再解释之前我们先看一个图，图如下：</p>

<div  align="center"><img src="https://wejack639.oss-cn-beijing.aliyuncs.com/blogimages/img/20221104105340.png" width = 500 /></div>

<div  align="center"><img src="https://wejack639.oss-cn-beijing.aliyuncs.com/blogimages/img/20221104105425.png" width = 600 /></div>

<p>相信学过汇编的朋友都很熟悉这张图，这张图就是CPU与内存如何进行数据交换的模型，其中，左边蓝色的方框是CPU，右边绿色的方框是内存，内存上面的0～3是内存地址。这里我们这张图是以32位CPU作为代表，我们都知道，32位CPU是以双字（DWORD）为单位进行数据传输的，也正因为这点，造成了另外一个问题，那么这个问题是什么呢？这个问题就是，既然32位CPU以双字进行数据传输，那么，如果我们的数据只有8位或16位数据的时候，是不是CPU就按照我们数据的位数来进行数据传输呢？其答案是否定的，如果这样会使得CPU硬件变的更复杂，所以32位CPU传输数据无论是8位或16位都是以双字进行数据传输。那么也罢，8位或16位一样可以传输，但是，事情并非像我们想象的那么简单，比如，一个int类型4字节的数据如果放在上图内存地址1开始的位置，那么这个数据占用的内存地址为1～4，那么这个数据就被分为了2个部分，一个部分在地址0～3中，另外一部分在地址4～7中，又由于32位CPU以双字进行传输，所以，CPU会分2次进行读取，一次先读取地址0～3中内容，再一次读取地址4～7中数据，最后CPU提取并组合出正确的int类型数据，舍弃掉无关数据。那么反过来，如果我们把这个int类型4字节的数据放在上图从地址0开始的位置会怎样呢？读到这里，也许你明白了，CPU只要进行一次读取就可以得到这个int类型数据了。没错，就是这样，这次CPU只用了一个周期就得到了数据，由此可见，对内存数据的摆放是多么重要啊，摆放正确位置可以减少CPU的使用资源。</p>

<p>那么，内存对齐有哪些原则呢？我总结了一下大致分为三条：</p>

<ul>
<li><strong>第一条：第一个成员的首地址为0</strong></li>

<li><p><strong>第二条：每个成员的首地址是自身大小的整数倍</strong></p>

<ul>
<li>第二条补充：以4字节对齐为例，如果自身大小大于4字节，都以4字节整数倍为基准对齐。若内嵌结构体，则内嵌结构体的首地址也要符合此条，只不过自身大小用内嵌结构体的最大成员来表示。补齐时，内嵌结构体和外部结构体都要满足补齐，内嵌机构体中的补齐以其内部最大成员表示；外部结构体以自身基础成员和内嵌结构体的最大成员之间的较大者表示。</li>
</ul></li>

<li><p><strong>第三条：最后以结构总体对齐。</strong></p>

<ul>
<li>第三条补充：以4字节对齐为例，取结构体中最大成员类型倍数，如果超过4字节，都以4字节整数倍为基准对齐。（其中这一条还有个名字叫：“补齐”，补齐的目的就是多个结构变量挨着摆放的时候也满足对齐的要求。）</li>
</ul></li>
</ul>

<p>上述的三原则听起来还是比较抽象，那么接下来我们通过一个例子来加深对内存对齐概念的理解，下面是一个结构体，我们动手算出下面结构体一共占用多少内存？假设我们以32位平台并且以4字节对齐方式：</p>
<div class="highlight"><pre style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-c" data-lang="c"><span style="color:#8f5902;font-style:italic">#</span><span style="color:#8f5902;font-style:italic">pragma pack(4)  </span><span style="color:#8f5902;font-style:italic">
</span><span style="color:#8f5902;font-style:italic"></span><span style="color:#204a87;font-weight:bold">typedef</span> <span style="color:#204a87;font-weight:bold">struct</span> <span style="color:#000">MemAlign</span>  
<span style="color:#000;font-weight:bold">{</span>  
    <span style="color:#204a87;font-weight:bold">char</span> <span style="color:#000">a</span><span style="color:#000;font-weight:bold">[</span><span style="color:#0000cf;font-weight:bold">18</span><span style="color:#000;font-weight:bold">]</span><span style="color:#000;font-weight:bold">;</span>  
    <span style="color:#204a87;font-weight:bold">double</span> <span style="color:#000">b</span><span style="color:#000;font-weight:bold">;</span>     
    <span style="color:#204a87;font-weight:bold">char</span> <span style="color:#000">c</span><span style="color:#000;font-weight:bold">;</span>  
    <span style="color:#204a87;font-weight:bold">int</span> <span style="color:#000">d</span><span style="color:#000;font-weight:bold">;</span>    
    <span style="color:#204a87;font-weight:bold">short</span> <span style="color:#000">e</span><span style="color:#000;font-weight:bold">;</span>      
<span style="color:#000;font-weight:bold">}</span><span style="color:#000">MemAlign</span><span style="color:#000;font-weight:bold">;</span> </code></pre></div>
<p>下图为对齐后结构如下：</p>

<div  align="center"><img src="https://wejack639.oss-cn-beijing.aliyuncs.com/blogimages/img/20221104110123.png" width = 400 /> </div>

<p>我们就以这个图来讲解是如何对齐的：
第一个成员（char a[18]）：首先，假设我们把它放到内存开始地址为0的位置，由于第一个成员占18个字节，所以第一个成员占用内存地址范围为0～18。
第二个成员（double b）：由于double类型占8字节，又因为8字节大于4字节，所以就以4字节对齐为基准。由于第一个成员结束地址为18，那么地址18并不是4的整数倍，我们需要再加2个字节，也就是从地址20开始摆放第二个成员。
第三个成员（char c）：由于char类型占1字节，任意地址是1字节的整数倍，所以我们就直接将其摆放到紧接第二个成员之后即可。
第四个成员（int d）：由于int类型占4字节，但是地址29并不是4的整数倍，所以我们需要再加3个字节，也就是从地址32开始摆放这个成员。
第五个成员（short e）：由于short类型占2字节，地址36正好是2的整数倍，这样我们就可以直接摆放，无需填充字节,紧跟其后即可。
  这样我们内存对齐就完成了。但是离成功还差那么一步，那是什么呢？对，是对整个结构体补齐，接下来我们就补齐整个结构体。那么，先让我们回顾一下补齐的原则：“以4字节对齐为例，取结构体中最大成员类型倍数，如果超过4字节，都以4字节整数倍为基准对齐。”在这个结构体中最大类型为double类型（占8字节），又由于8字节大于4字 节，所以我们还是以4字节补齐为基准，整个结构体结束地址为38，而地址38并不是4的整数倍，所以我们还需要加额外2个字节来填充结构体，如下图红色的就是补齐出来的空间：</p>

<div  align="center"><img src="https://wejack639.oss-cn-beijing.aliyuncs.com/blogimages/img/20221104112337.png" width = 400 /> </div>

<p>到此为止，我们内存对齐与补齐就完毕了！接下来我们用实验来证明真理，程序如下：</p>
<div class="highlight"><pre style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-c" data-lang="c"><span style="color:#8f5902;font-style:italic">#</span><span style="color:#8f5902;font-style:italic">include</span> <span style="color:#8f5902;font-style:italic">&lt;stdio.h&gt;  </span><span style="color:#8f5902;font-style:italic">
</span><span style="color:#8f5902;font-style:italic"></span><span style="color:#8f5902;font-style:italic">#</span><span style="color:#8f5902;font-style:italic">include</span> <span style="color:#8f5902;font-style:italic">&lt;memory.h&gt;  </span><span style="color:#8f5902;font-style:italic">
</span><span style="color:#8f5902;font-style:italic"></span>  
<span style="color:#8f5902;font-style:italic">// 由于VS2010默认是8字节对齐，我们  
</span><span style="color:#8f5902;font-style:italic"></span><span style="color:#8f5902;font-style:italic">// 通过预编译来通知编译器我们以4字节对齐  
</span><span style="color:#8f5902;font-style:italic"></span><span style="color:#8f5902;font-style:italic">#</span><span style="color:#8f5902;font-style:italic">pragma pack(4)  </span><span style="color:#8f5902;font-style:italic">
</span><span style="color:#8f5902;font-style:italic"></span>  
<span style="color:#8f5902;font-style:italic">// 用于测试的结构体  
</span><span style="color:#8f5902;font-style:italic"></span><span style="color:#204a87;font-weight:bold">typedef</span> <span style="color:#204a87;font-weight:bold">struct</span> <span style="color:#000">MemAlign</span>  
<span style="color:#000;font-weight:bold">{</span>  
    <span style="color:#204a87;font-weight:bold">char</span> <span style="color:#000">a</span><span style="color:#000;font-weight:bold">[</span><span style="color:#0000cf;font-weight:bold">18</span><span style="color:#000;font-weight:bold">]</span><span style="color:#000;font-weight:bold">;</span> <span style="color:#8f5902;font-style:italic">// 18 bytes  
</span><span style="color:#8f5902;font-style:italic"></span>    <span style="color:#204a87;font-weight:bold">double</span> <span style="color:#000">b</span><span style="color:#000;font-weight:bold">;</span>   <span style="color:#8f5902;font-style:italic">// 08 bytes   
</span><span style="color:#8f5902;font-style:italic"></span>    <span style="color:#204a87;font-weight:bold">char</span> <span style="color:#000">c</span><span style="color:#000;font-weight:bold">;</span>     <span style="color:#8f5902;font-style:italic">// 01 bytes  
</span><span style="color:#8f5902;font-style:italic"></span>    <span style="color:#204a87;font-weight:bold">int</span> <span style="color:#000">d</span><span style="color:#000;font-weight:bold">;</span>      <span style="color:#8f5902;font-style:italic">// 04 bytes  
</span><span style="color:#8f5902;font-style:italic"></span>    <span style="color:#204a87;font-weight:bold">short</span> <span style="color:#000">e</span><span style="color:#000;font-weight:bold">;</span>    <span style="color:#8f5902;font-style:italic">// 02 bytes  
</span><span style="color:#8f5902;font-style:italic"></span><span style="color:#000;font-weight:bold">}</span><span style="color:#000">MemAlign</span><span style="color:#000;font-weight:bold">;</span>  
  
<span style="color:#204a87;font-weight:bold">int</span> <span style="color:#000">main</span><span style="color:#000;font-weight:bold">(</span><span style="color:#000;font-weight:bold">)</span>  
<span style="color:#000;font-weight:bold">{</span>  
    <span style="color:#8f5902;font-style:italic">// 定义一个结构体变量  
</span><span style="color:#8f5902;font-style:italic"></span>    <span style="color:#000">MemAlign</span> <span style="color:#000">m</span><span style="color:#000;font-weight:bold">;</span>  
    <span style="color:#8f5902;font-style:italic">// 定义个以指向结构体指针  
</span><span style="color:#8f5902;font-style:italic"></span>    <span style="color:#000">MemAlign</span> <span style="color:#ce5c00;font-weight:bold">*</span><span style="color:#000">p</span> <span style="color:#ce5c00;font-weight:bold">=</span> <span style="color:#ce5c00;font-weight:bold">&amp;</span><span style="color:#000">m</span><span style="color:#000;font-weight:bold">;</span>  
    <span style="color:#8f5902;font-style:italic">// 依次对各个成员进行填充，这样我们可以  
</span><span style="color:#8f5902;font-style:italic"></span>    <span style="color:#8f5902;font-style:italic">// 动态观察内存变化情况  
</span><span style="color:#8f5902;font-style:italic"></span>    <span style="color:#000">memset</span><span style="color:#000;font-weight:bold">(</span> <span style="color:#ce5c00;font-weight:bold">&amp;</span><span style="color:#000">m</span><span style="color:#000;font-weight:bold">.</span><span style="color:#000">a</span><span style="color:#000;font-weight:bold">,</span> <span style="color:#0000cf;font-weight:bold">0x11</span><span style="color:#000;font-weight:bold">,</span> <span style="color:#204a87;font-weight:bold">sizeof</span><span style="color:#000;font-weight:bold">(</span><span style="color:#000">m</span><span style="color:#000;font-weight:bold">.</span><span style="color:#000">a</span><span style="color:#000;font-weight:bold">)</span> <span style="color:#000;font-weight:bold">)</span><span style="color:#000;font-weight:bold">;</span>  
    <span style="color:#000">memset</span><span style="color:#000;font-weight:bold">(</span> <span style="color:#ce5c00;font-weight:bold">&amp;</span><span style="color:#000">m</span><span style="color:#000;font-weight:bold">.</span><span style="color:#000">b</span><span style="color:#000;font-weight:bold">,</span> <span style="color:#0000cf;font-weight:bold">0x22</span><span style="color:#000;font-weight:bold">,</span> <span style="color:#204a87;font-weight:bold">sizeof</span><span style="color:#000;font-weight:bold">(</span><span style="color:#000">m</span><span style="color:#000;font-weight:bold">.</span><span style="color:#000">b</span><span style="color:#000;font-weight:bold">)</span> <span style="color:#000;font-weight:bold">)</span><span style="color:#000;font-weight:bold">;</span>  
    <span style="color:#000">memset</span><span style="color:#000;font-weight:bold">(</span> <span style="color:#ce5c00;font-weight:bold">&amp;</span><span style="color:#000">m</span><span style="color:#000;font-weight:bold">.</span><span style="color:#000">c</span><span style="color:#000;font-weight:bold">,</span> <span style="color:#0000cf;font-weight:bold">0x33</span><span style="color:#000;font-weight:bold">,</span> <span style="color:#204a87;font-weight:bold">sizeof</span><span style="color:#000;font-weight:bold">(</span><span style="color:#000">m</span><span style="color:#000;font-weight:bold">.</span><span style="color:#000">c</span><span style="color:#000;font-weight:bold">)</span> <span style="color:#000;font-weight:bold">)</span><span style="color:#000;font-weight:bold">;</span>  
    <span style="color:#000">memset</span><span style="color:#000;font-weight:bold">(</span> <span style="color:#ce5c00;font-weight:bold">&amp;</span><span style="color:#000">m</span><span style="color:#000;font-weight:bold">.</span><span style="color:#000">d</span><span style="color:#000;font-weight:bold">,</span> <span style="color:#0000cf;font-weight:bold">0x44</span><span style="color:#000;font-weight:bold">,</span> <span style="color:#204a87;font-weight:bold">sizeof</span><span style="color:#000;font-weight:bold">(</span><span style="color:#000">m</span><span style="color:#000;font-weight:bold">.</span><span style="color:#000">d</span><span style="color:#000;font-weight:bold">)</span> <span style="color:#000;font-weight:bold">)</span><span style="color:#000;font-weight:bold">;</span>  
    <span style="color:#000">memset</span><span style="color:#000;font-weight:bold">(</span> <span style="color:#ce5c00;font-weight:bold">&amp;</span><span style="color:#000">m</span><span style="color:#000;font-weight:bold">.</span><span style="color:#000">e</span><span style="color:#000;font-weight:bold">,</span> <span style="color:#0000cf;font-weight:bold">0x55</span><span style="color:#000;font-weight:bold">,</span> <span style="color:#204a87;font-weight:bold">sizeof</span><span style="color:#000;font-weight:bold">(</span><span style="color:#000">m</span><span style="color:#000;font-weight:bold">.</span><span style="color:#000">e</span><span style="color:#000;font-weight:bold">)</span> <span style="color:#000;font-weight:bold">)</span><span style="color:#000;font-weight:bold">;</span>  
    <span style="color:#8f5902;font-style:italic">// 由于有补齐原因，所以我们需要对整个  
</span><span style="color:#8f5902;font-style:italic"></span>    <span style="color:#8f5902;font-style:italic">// 结构体进行填充，补齐对齐剩下的字节  
</span><span style="color:#8f5902;font-style:italic"></span>    <span style="color:#8f5902;font-style:italic">// 以便我们可以观察到变化  
</span><span style="color:#8f5902;font-style:italic"></span>    <span style="color:#000">memset</span><span style="color:#000;font-weight:bold">(</span> <span style="color:#ce5c00;font-weight:bold">&amp;</span><span style="color:#000">m</span><span style="color:#000;font-weight:bold">,</span> <span style="color:#0000cf;font-weight:bold">0x66</span><span style="color:#000;font-weight:bold">,</span> <span style="color:#204a87;font-weight:bold">sizeof</span><span style="color:#000;font-weight:bold">(</span><span style="color:#000">m</span><span style="color:#000;font-weight:bold">)</span> <span style="color:#000;font-weight:bold">)</span><span style="color:#000;font-weight:bold">;</span>  
    <span style="color:#8f5902;font-style:italic">// 输出结构体大小  
</span><span style="color:#8f5902;font-style:italic"></span>    <span style="color:#000">printf</span><span style="color:#000;font-weight:bold">(</span> <span style="color:#4e9a06"></span><span style="color:#4e9a06">&#34;</span><span style="color:#4e9a06">sizeof(MemAlign) = %d</span><span style="color:#4e9a06">&#34;</span><span style="color:#000;font-weight:bold">,</span> <span style="color:#204a87;font-weight:bold">sizeof</span><span style="color:#000;font-weight:bold">(</span><span style="color:#000">m</span><span style="color:#000;font-weight:bold">)</span> <span style="color:#000;font-weight:bold">)</span><span style="color:#000;font-weight:bold">;</span>  
<span style="color:#000;font-weight:bold">}</span>  </code></pre></div>
<p>程序运行过程中，查看内存如下：</p>

<div  align="center"><img src="https://wejack639.oss-cn-beijing.aliyuncs.com/blogimages/img/20221104112440.png" width = 700 /> </div>

<p>其中，各种颜色带下划线的代表各个成员变量，蓝色方框的代表为内存对齐时候填补的多余字节，由于这里看不到补齐效果，我们接下来看下图，下图篮框包围的字节就是与上图的交集以外的部分就是补齐所填充的字节。</p>

<div  align="center"><img src="https://wejack639.oss-cn-beijing.aliyuncs.com/blogimages/img/20221104112602.png" width = 700 /> </div>

<p>在最后，我在谈一谈关于补齐的作用，补齐其实就是为了让这个结构体定义的数组变量时候，数组内部，也同样满足内存对齐的要求，为了更好的理解这点，我做了一个跟本例子相对照的图：</p>

<div  align="center"><img src="https://wejack639.oss-cn-beijing.aliyuncs.com/blogimages/img/20221104112625.png" width = 700 /> </div>

<p>补充：</p>

<p>1）对于结构体中有数组的，将数组作为基本数据类型来处理对齐；</p>

<p>2）对于结构体内嵌套结构体成员的，结构体成员的对齐和补齐原则：已最大成员作为内结构体整体的大小去匹配；</p>

    </div>
    <footer class="post-footer">
     
 
<div class="post-tags">     
     
    <a href="http://www.shutdown.cn/tags/linux" rel="tag" title="linux">#linux#</a>
    
    <a href="http://www.shutdown.cn/tags/c" rel="tag" title="c">#c#</a>
    
    <a href="http://www.shutdown.cn/tags/%e7%bb%93%e6%9e%84%e4%bd%93" rel="tag" title="结构体">#结构体#</a>
    
    <a href="http://www.shutdown.cn/tags/%e5%af%b9%e9%bd%90" rel="tag" title="对齐">#对齐#</a>
    
</div>



     <div class="post-nav">
    <div class="post-nav-next post-nav-item">
    
        <a href="http://www.shutdown.cn/post/markdown/" rel="next" title="markdown语法">
        <i class="fa fa-chevron-left"></i> markdown语法
        </a>
    
    </div>

    <div class="post-nav-prev post-nav-item">
    
        <a href="http://www.shutdown.cn/post/redis-scan%E8%BF%94%E5%9B%9E%E6%95%B0%E6%8D%AE%E9%87%8F%E5%A4%A7%E4%BA%8Elimit%E7%9A%84count%E5%8E%9F%E5%9B%A0%E5%88%86%E6%9E%90/" rel="prev" title="">
         <i class="fa fa-chevron-right"></i>
        </a>
    
    </div>
</div>
      
     
     
     






    </footer>
  </article>
</section>

          </div>
        </div>
        <div class="sidebar-toggle">
  <div class="sidebar-toggle-line-wrap">
    <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
    <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
    <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
  </div>
</div>
<aside id="sidebar" class="sidebar">
  <div class="sidebar-inner">

  <ul class="sidebar-nav motion-element">
    <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
      文章目录
    </li>
    <li class="sidebar-nav-overview" data-target="site-overview">
      站点概览
    </li>
  </ul>

    <section class="site-overview sidebar-panel ">
      <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image"
        src="http://www.shutdown.cn/img/author.jpg"
        alt="不与天斗Domino" />
    <p class="site-author-name" itemprop="name">不与天斗Domino</p>
    <p class="site-description motion-element" itemprop="description"> 
        Programmer &amp; Architect</p>
</div>
      <nav class="site-state motion-element">
    <div class="site-state-item site-state-posts">
      <a href="http://www.shutdown.cn/post/">
        <span class="site-state-item-count">183</span>
        <span class="site-state-item-name">日志</span>
      </a>
    </div>
    <div class="site-state-item site-state-categories">    
        <a href="http://www.shutdown.cn/categories/">      
         
        <span class="site-state-item-count">15</span>
        
        <span class="site-state-item-name">分类</span>
        
        </a>
    </div>

    <div class="site-state-item site-state-tags">
        <a href="http://www.shutdown.cn/tags/">
         
        <span class="site-state-item-count">224</span>
        
        <span class="site-state-item-name">标签</span>
        </a>
    </div>
</nav>
      
      

      

      <div class="links-of-blogroll motion-element inline">
<script type="text/javascript" src="//rf.revolvermaps.com/0/0/8.js?i=&amp;m=0&amp;s=220&amp;c=ff0000&amp;cr1=ffffff&amp;f=arial&amp;l=33&amp;bv=35" async="async"></script>
</div>

    </section>
    
<section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
    <div class="post-toc">
        <div class="post-toc-content"></div>
    </div>
</section>

  </div>
</aside>

      </div>
    </main>
   
    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  <span itemprop="copyrightYear">  &copy; 
  2013 - 2023</span>
  <span class="with-love"><i class="fa fa-heart"></i></span>
  <span class="author" itemprop="copyrightHolder">天地维杰网</span>
  <span class="icp" itemprop="copyrightHolder"><a href="https://beian.miit.gov.cn/" target="_blank">京ICP备13019191号-1</a></span>
</div>
<div class="powered-by">
  Powered by - <a class="theme-link" href="http://gohugo.io" target="_blank" title="hugo" >Hugo v0.63.2</a>
</div>
<div class="theme-info">
  Theme by - <a class="theme-link" href="https://github.com/xtfly/hugo-theme-next" target="_blank"> NexT
  </a>
</div>


      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
      <span id="scrollpercent"><span>0</span>%</span>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>
<script type="text/javascript" src="http://www.shutdown.cn/js/vendor/jquery/index.js?v=2.1.3"></script>
<script type="text/javascript" src="http://www.shutdown.cn/js/vendor/fastclick/lib/fastclick.min.js?v=1.0.6"></script> 
<script type="text/javascript" src="http://www.shutdown.cn/js/vendor/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
<script type="text/javascript" src="http://www.shutdown.cn/js/vendor/velocity/velocity.min.js?v=1.2.1"></script>
<script type="text/javascript" src="http://www.shutdown.cn/js/vendor/velocity/velocity.ui.min.js?v=1.2.1"></script>
<script src="http://www.shutdown.cn/js/vendor/ua-parser-js/dist/ua-parser.min.js?v=0.7.9"></script>

<script src="http://www.shutdown.cn/js/vendor/fancybox/jquery.fancybox.pack.js?v=2.1.5"></script>

<script type="text/javascript" src="http://www.shutdown.cn/js/utils.js"></script>
<script type="text/javascript" src="http://www.shutdown.cn/js/motion.js"></script>
<script type="text/javascript" src="http://www.shutdown.cn/js/affix.js"></script>
<script type="text/javascript" src="http://www.shutdown.cn/js/schemes/pisces.js"></script>

<script type="text/javascript" src="http://www.shutdown.cn/js/scrollspy.js"></script>
<script type="text/javascript" src="http://www.shutdown.cn/js/post-details.js"></script>
<script type="text/javascript" src="http://www.shutdown.cn/js/toc.js"></script>

<script type="text/javascript" src="http://www.shutdown.cn/js/bootstrap.js"></script>

<script type="text/javascript" src="http://www.shutdown.cn/js/search.js"></script>
<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
    extensions: ["tex2jax.js"],
    jax: ["input/TeX", "output/HTML-CSS"],
    tex2jax: {
      inlineMath: [ ['$','$'] ],
      displayMath: [ ['$$','$$'] ],
      processEscapes: true
    },
    "HTML-CSS": { fonts: ["TeX"] }
  });
</script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-AMS-MML_HTMLorMML' async></script>
</body>
</html>